<template>
	<view class="qr_container">
		<!-- <view class="change_box">
			<view class="m_h_box" @click="showOrg = true">
				<text class="m_h_title">{{orgMsg?orgMsg:'当前无绑定人员'}}</text>
				<view class="m_h_r_box">
					<view class="change_btn">
						<text>切换</text>
						<image class="change_icon" src="/static/images/right.png" mode="scaleToFill"></image>
					</view>
				</view>
			</view>
		</view> -->
		<view class="qrcode_swiper">
			<swiper :indicator-dots="ranges[0]?ranges[0].length > 1:false" class="swiper" current="0" @change="_changOrg">
				<swiper-item v-for="(item, index) in ranges[0]" :key="index">
					<view class="qrcode">
						<view class="msg_box">
							<view>
								<picker @change="(e) => {_changeCard(e, item)}" :value="cardIndex" range-key="txt"  :range="ranges[1]">
									<view class="stu_name">{{ranges[1]?ranges[1][cardIndex].empName:''}}<image v-if="ranges[1]?ranges[1].length > 1:false" src="../../static/images/me/to_right_icon.png" mode="scaleToFill"></image></view>
								</picker>
							</view>
							<view class="stu_org">
								{{item.orgName}}
							</view>
						</view>
						<view class="qrcode_box">
							<!-- #ifndef MP-ALIPAY -->
							<canvas v-if="!showOrg" style="width: 200px;height: 200px;" :canvas-id="'code_'+item.orgId"></canvas>
							<!-- #endif -->
							<!-- #ifdef MP-ALIPAY -->
							<canvas v-if="!showOrg" style="width: 200px;height: 200px;" :id="'code_'+item.orgId"></canvas>
							<!-- #endif -->
						</view>
						<view>
							<text class="qr_txt" v-if="refreshNum == 0">{{txtActive}}</text>
							<view style="padding-top: 50rpx;" v-if="refreshNum != 0">
								<view class="boxs" @click="refresh">
									<image src="/static/images/home/refresh.png" class="imgava"></image>
									<text class="qr_re">如果二维码失效请点击刷新</text>
								</view>
							</view>
							<view v-if="refreshNum == 0">
								<view class="boxs" @click="refresh">
									<image src="/static/images/home/refresh.png" class="imgava"></image>
									<text class="qr_re">如果二维码失效请点击刷新</text>
								</view>
							</view>
						</view>
					</view>	
				</swiper-item>
			</swiper>
		</view>
		<custom-modal :isShow="showModal" :content="content" title="温馨提示" :showCancel="false" :inp="false" @ok='confirm()'/>
	</view>
</template>

<script>
	let _this;
	import {/* queryStudentCard, */ refreshQRCode, queryStudentCardBalance, milkQRCode, selectMilkByCode} from '../../common/api/index.js';
	const qrCode = require('../../common/js/weapp-qrcode.js');
	import { showLoading, hideLoading } from '../../common/js/loading.js';
	import {_showToast} from '../../common/js/util.js'
	import changeOrgs from '../../components/changeOrgs.vue'
	export default {
		data() {
			return {
				showOrg: false,
				array: ['中国', '美国', '巴西', '日本'],
				 index: 0,
				ranges: [],
				cardList: [],
				cardIndex: 0,
				dataVal: [0, 0],
				text: null,
				refreshNum: 0,
				timer: null,
				txtActive: '',
				orgId: '',
				empId: '',
				empName: '',
				orgMsg: '',
				bindType: "0,1",
				appType: uni.getStorageSync("app_type"),
				orgType: 0,
				codeStatusTimer: null,
				showModal: false,
				content: '',
			}
		},
		components: {
			changeOrgs
		},
		destroyed() {
			clearInterval(this.timer)
			clearTimeout(this.codeStatusTimer)
		},
		onLoad(option) {
			_this = this
			// 页面首次加载二维码，并判断上一次使用的二维码机构和人员
			const ORGDATA = null/* uni.getStorageSync('ORGDATA') */
			_this._queryStudentCardBalance(ORGDATA ? ORGDATA[0].orgId : false, true) 
		},
		onShow(){
			if(_this.orgId != '' || _this.empId != ''){
				_this.refresh() 
			}
		},
		methods: {
			   bindPickerChange: function(e) {
			            console.log('picker发送选择改变，携带值为', e.detail.value)
			            this.index = e.detail.value
			        },
			// 获取当前二维码状态
			_selectMilkByCode(){
				clearTimeout(this.codeStatusTimer)
				selectMilkByCode({code: this.text}).then(res => {
					if(res.code == 0){
						if(res.data == null || res.data.payStatus == 4){
							if(res.data){
								uni.showLoading({
									title: '支付中'
								})
							}
							this.codeStatusTimer = setTimeout(()=>{
								this._selectMilkByCode()
							}, 3000)
						}else{
							if(res.data.payStatus == 1){
								this.codeStatusTimer = setTimeout(()=>{
									this._selectMilkByCode()
								}, 3000)
							}else {
								uni.navigateTo({
									url:`../../pageMilk/qrcode/end?recordsData=${JSON.stringify(res.data)}`
								})
							}
						}
					} 
				}).catch(err => {console.log(err)})
			},
			// 设置二维码过期监控
			_set() {
			  this.timer = setInterval(() => {
				  this.refreshNum = this.refreshNum - 1
				  if(this.refreshNum == 0) {
					clearInterval(this.timer)
					clearTimeout(this.codeStatusTimer)
					this.txtActive = '二维码已过期!'
				  }
			  }, 1000)
			},
			// 刷新二维码
			refresh() {
				if(_this.orgType != 3){
					_this._getQrCode()
				}else{
					_this._getMilkQrCode()
				}
				let timers = setTimeout(() => {
					_showToast('刷新成功')
				}, 60)
				if(timers) clearTimeout(timers)
			},
			// 获取小达二维码
			_getQrCode() {
				let s_userId = uni.getStorageSync('s_userId')
				clearInterval(this.timer)
				clearTimeout(this.codeStatusTimer)
				showLoading()
				refreshQRCode({
					userId: s_userId,
					empId: this.empId,
					orgId: this.orgId
				}).then(res => {
					// console.log(res,"这里")
					if(res.resultCode == 0) {
						hideLoading()
						this.text = res.qrcode
						this.refreshNum = res.validTime
						this.couponQrCode('code_' + this.orgId)
						this._set()
					} else {
						// _showToast(res.resultMsg)
						this.showModal = true
						this.content = res.resultMsg
						hideLoading()
					}
				}).catch(err => {
					hideLoading()
					console.log(err)
				})
			},
			// 获取奶机构二维码
			_getMilkQrCode() {
				let s_userId = uni.getStorageSync('s_userId')
				clearInterval(this.timer)
				clearTimeout(this.codeStatusTimer)
				showLoading()
				milkQRCode({
					userId: s_userId,
					empId: this.empId,
					orgId: this.orgId
				}).then(res => {
					if(res.resultCode == 0) {
						hideLoading()
						this.text = res.qrcode
						this.refreshNum = res.validTime
						this.couponQrCode('code_' + this.orgId)
						this._set()
					} else {
						_showToast(res.resultMsg)
						hideLoading()
					}
				}).catch(err => {
					hideLoading()
					console.log(err)
				})
			},
			// 可选机构加载
			_queryStudentCardBalance(orgId, first) {
				uni.showLoading({
					mask: true,
					title: '加载中...'
				})
				let s_userId = uni.getStorageSync('s_userId')
				queryStudentCardBalance({
					userId: s_userId,
					orgId: orgId?orgId:null,
					queryCard: true,
					queryWallet: true,
					bindType: this.bindType
				}).then(res => {
					if (res.code == 0) {
						let students = res.data.students,orgs = res.data.orgs
						let lv1 = [],lv2 = [];
						
						uni.hideLoading()
						orgs.forEach((item,index) => {
							item.value = item.orgId
							item.txt = item.orgName
							item.index = index
							let a
							if(lv1.length>0){
								if(lv1.some(i=>i.orgId==item.orgId)){
								}else{
									lv1.push(item)
								}
							}else{
								lv1.push(item)
							}
						})
						
						console.log(lv1)
						students.forEach((item,index) => {
							let stu = item.students[0]
							if(stu.cards.length > 0) {
								stu.value = stu.orgId
								stu.txt = stu.empName
								stu.bindType = item.bindType
								stu.index = index
							
								lv2.push(stu)
							}
						})
						this.array=lv2
						console.log(this.array)
						_this.ranges = [lv1, lv2]
						console.log(_this.ranges[1])
						// 用户第一次使用二维码时
						// if(!orgId){
						// 	_this._confirmStudent([lv1[0],lv2[0]])
						// }else {
							// 页面首次加载时判断是否上次使用二维码
							// if(first){
							// 	const ORGDATA = uni.getStorageSync('ORGDATA')
							// 	_this._confirmStudent(ORGDATA && first ? ORGDATA :[lv1[0],lv2[0]])
								// _this.dataVal = ORGDATA && first ? [ORGDATA[0].index, ORGDATA[1].index] :[0,0]
							// }else {
								_this._confirmStudent([lv1[0],lv2[0]])
							// }
							
						// }
						
					} else {
						uni.hideLoading()
						_this.ranges = []
					}
				}).catch(err => {
					uni.hideLoading()
					console.log(err)
				})
			},
			//确认用户
			_confirmStudent(data){
				// 保存这一次打开的二维码
				uni.setStorageSync("ORGDATA", data)
				console.log(data)
				_this.orgId = data[1].orgId;
				_this.empId = data[1].empId;
				_this.empName = data[1].empName;
				_this.orgMsg = data[1].orgName + '(' + data[1].empName + ')';
				_this.orgType = data[1].bindType;
				if(_this.orgType != 3){
					_this._getQrCode()
				}else{
					_this._getMilkQrCode()
				}
			},
				// 选择机构
			
			_SchoolsChange(data) {
				if(data[0].value == _this.orgId) return
				_this.orgId = data[0].value
				_this._queryStudentCardBalance(data[0].value)
			},

			_changOrg(e){

				const data = [{value: _this.ranges[0][e.detail.current].orgId}]
				console.log(data)
				this.cardIndex = 0
				_this._SchoolsChange(data)
			},
			_changeCard(e, org){
				this.cardIndex = e.detail.value
				this._confirmStudent([org, this.ranges[1][this.cardIndex]])
			},
			// 渲染二维码
			couponQrCode(cavansId) {
				if(_this.orgType == 3){
					_this._selectMilkByCode()
				}
				new qrCode(cavansId, {
					text: this.text,
					width: 200,
					height: 200,
					colorDark: "#333333",
					colorLight: "#FFFFFF",
					correctLevel: qrCode.CorrectLevel.Q
				})
			},
			// 信息提示确认
			confirm(){
				this.showModal = false
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #FFFFFF;
	}
	
	.change_box {
		width: 100vw;
		display: flex;
		justify-content: center;
	}
	.m_h_box {
		margin-top: 80rpx;
		width: 85%;
		height: 96rpx;
		background: rgba(255, 255, 255, 0.38);
		box-shadow: 0 8rpx 16rpx 0 rgba(0, 0, 0, 0.28);
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
		border-radius: 8rpx;
		padding: 0 26rpx;
	}
	.m_h_title {
		font-size: 30rpx;
		font-family: "PingFangSC-Semibold, PingFang SC";
		font-weight: 600;
		color: #FFFFFF;
	}
	.m_h_r_box {
		display: flex;
		flex-direction: row;
		align-items: center;
		background: linear-gradient(180deg, #FFFFFF 0%, #E3E8FF 100%);
		border-radius: 30rpx;
		justify-content: center;
	}
	.uni-input {
		padding: 0;
		background: none;
	}
	
	.change_btn {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-around;
		height: 52rpx;
		line-height: 52rpx;
		background: linear-gradient(180deg, #FFFFFF 0%, #E3E8FF 100%);
		border-radius: 32px;
		padding: 0 24rpx;
		color: #144DE8;
		font-size: 24rpx;
	}
	
	.change_icon {
		width: 32rpx;
		height: 32rpx;
	}
	.qrcode_swiper{
		width: 100%;
		height: 100%;
	}
	.swiper{
		width: 100%;
		height: 1100rpx;
	}
	.qr_container {
		width: 100vw;
		height: 100vh;
		background-image: url('');
		background-size: 100% 100%;
		background-repeat: no-repeat;
		display: flex;
		flex-direction: column;
		align-items: center;
		.qrcode {
			background: #FFFFFF;
			box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.18);
			border-radius: 10rpx;
			padding: 40rpx;
			width: 80%;
			box-sizing: border-box;
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translate(-50%, -50%);
			.qrcode_box {
				width: calc(100% - 40rpx);
				display: flex;
				justify-content: center;
				height: 200px;
				padding: 20rpx;
			}
			.qr_txt {
				font-family: 'PingFangSC';
				font-weight: 400;
				font-size: 32rpx;
				color: red;
				padding: 30rpx 0;
				text-align: center;
				width: 100%;
				display: block;
			}
			.boxs {
				display: flex;
				flex-direction: row;
				align-items: center;
				justify-content: center;
				.imgava {
					width: 50rpx;
					height: 50rpx; 
					margin-right: 15rpx;
				}
				.qr_re {
					font-size: 28rpx;
					font-family: "PingFangSC-Medium, PingFang SC";
					font-weight: 500;
					color: #6B707A;
				}
			}
			.msg_box{
				padding: 24rpx 0;
				.stu_name{
					display: flex;
					justify-content: space-between;
					align-items: center;
					font-size: 38rpx;
					image{
						width: 48rpx;
						height: 48rpx;
					}
				}
				.stu_org{
					font-size: 24rpx;
					color: #999;
				}
			}
		}
	}
	canvas {
		width: 400rpx;
		height: 400rpx;
	}
</style>
